package common.core;
import common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;


@Component
public class JwtInterceptor implements HandlerInterceptor {

    /**
     * 描述: 拦截器前置处理，将token中的载荷内容放入threadlocal中
     * 作者: lljm
     * 日期: 2024/6/6
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals(HttpMethod.OPTIONS.name())) {
            return true;
        }
        String token = request.getHeader("Authorization");
        if (token != null ) {
            try {
                Claims claims = JwtUtil.parseToken(token);

                // 校验 token 是否过期
                if (claims.getExpiration().before(new Date())) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token Expired");
                    return false;
                }

                // 这里将 payload 内容放入 ThreadLocal
                JwtPayloadHolder.setPayload(claims);

                //放行
                return true;
            } catch (Exception e) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid Token");
                return false;
            }
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing Token");
            return false;
        }
    }

    /**
     * 描述: 拦截器后置处理，清空 ThreadLocal
     * 作者: lljm
     * 日期: 2024/6/6
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        JwtPayloadHolder.clear();
    }
}
